package com.interview.ujiuye9;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareData{
    private Lock lock = new ReentrantLock();//创建锁对象
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int number = 1;//1--A线程 2---B线程 3---C线程

    //打印5次内容
    public void print5(){
        try
        {
            lock.lock();//加锁
            while (number != 1){
                condition1.await();//如果当前数据number不是1我就等待
            }
            for (int i=0 ; i< 5; i++){
                System.out.print("A");
            }
            number = 2;//修改标志位
            condition2.signal();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
    }

    //打印10次内容
    public void print10(){
        try
        {
            lock.lock();//加锁
            while (number != 2){
                condition2.await();//如果当前数据number不是1我就等待
            }
            for (int i=0 ; i< 10; i++){
                System.out.print("B");
            }
            number = 3;//修改标志位
            condition3.signal();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
    }

    //打印15次内容
    public void print15(){
        try
        {
            lock.lock();//加锁
            while (number != 3){
                condition3.await();//如果当前数据number不是1我就等待
            }
            for (int i=0 ; i< 15; i++){
                System.out.print("C");
            }
            number = 1;//修改标志位
            condition1.signal();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
    }
}
public class LockDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread( () ->{
            for (int i = 0; i < 10; i++) {
                shareData.print5();
            }
        },"A").start();

        new Thread( () -> {
            for (int i = 0; i < 10; i++) {
                shareData.print10();
            }
        },"B" ).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.print15();
            }
        }, "C").start();
    }
}
